import api from "../../api";
import router from "../../router";
export default {
	namespaced: true, // 具名模块化
	state: {
		token: localStorage.getItem("token") || "",
		name: "",
		id: "",
		avatar: "",
		role: "",
	},
	mutations: {
		setToken(state, token) {
			state.token = token;
			window.localStorage.setItem("token", token);
		},
		setRole(state, role) {
			state.role = role;
		},
		logout(state) {
			state.token = "";
			state.role = "";
			window.localStorage.setItem("vuex", "");
			router.push("/login");
		},
	},
	actions: {
		// 登录
		LOGIN(context, data) {
			return new Promise((resolve, reject) => {
				api.login(data)
					.then(res => {
						if (res.success) {
							context.commit("setToken", res.token);
						}
						resolve(res);
					})
					.catch(err => {
						reject(err);
					});
			});
		},
		// 获取用户信息
		GET_INFO(context) {
			return new Promise((resolve, reject) => {
				api.getInfo()
					.then(res => {
						if (res.success) {
							context.commit("setRole", res.role);
						}
						resolve(res);
					})
					.catch(err => {
						reject(err);
					});
			});
		},
	},
};
